﻿using Fishing.Abstractions;
using System.Collections.Generic;
using System.Windows;

namespace Fishing.Core
{
    public class ViewProvider : IViewProvider
    {
        private readonly IDictionary<string, Window> _maps = new Dictionary<string, Window>();

        public TView GetView<TView>()
            where TView : Window, new()
        {
            var typeName = typeof(TView).Name;

            if (_maps.ContainsKey(typeName))
            {
                return (TView)_maps[typeName];
            }

            var instance = new TView();
            instance.Closed += View_Closed;

            _maps.Add(typeName, instance);

            return instance;
        }

        public bool ExistsView<TView>()
            where TView : Window
        {
            return _maps.ContainsKey(typeof(TView).Name);
        }

        private void View_Closed(object? sender, System.EventArgs e)
        {
            if (sender is null)
            {
                return;
            }

            _maps.Remove(sender.GetType().Name);
        }
    }
}